package com.atliuzu.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atliuzu.bean.TrafficPageViewBean;
import com.atliuzu.utils.ClickHouseUtil;
import com.atliuzu.utils.DateFormatUtil;
import com.atliuzu.utils.MyKafkaUtil;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.WindowAssigner;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.triggers.Trigger;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.streaming.api.windowing.windows.Window;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collection;

/**
 * @Author : songyuan
 * @Description :
 * Date : 2022/8/20 9:22
 * @Version : 1.0
 */
/*
来源粒度页面浏览各窗口汇总    独立访客数 dwd 独立访客主题
                            跳出会话数 dwd 跳出会话主题
                            会话数  页面浏览数  停留时长   直接从 page 页面主题来读取

 */


public class DwsTrafficScNewPageViewWindow {

    public static void main(String[] args) throws Exception {

        //1.执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.状态后端
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                3, Time.days(1), Time.minutes(1)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage(
//                "hdfs://hadoop102:8020/ck"
//        );
//        System.setProperty("HADOOP_USER_NAME", "atguigu");

        //3.读取独立访客数  转换为 javabean 封装为流
        String uvTopic = "dwd_traffic_unique_visitor_detail";
        String groupId = "dws_traffic_sc_new_page_view_window";
        DataStreamSource<String> uvDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(uvTopic, groupId));
        SingleOutputStreamOperator<TrafficPageViewBean> uvJBDS = uvDS.map(new MapFunction<String, TrafficPageViewBean>() {
            @Override
            public TrafficPageViewBean map(String value) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(value);

                return new TrafficPageViewBean(
                        "",
                        "",
                        jsonObject.getJSONObject("common").getString("sc"),
                        0L,
                        1L,
                        0L,
                        0L,
                        0L,
                        jsonObject.getLong("ts")
                );
            }
        });

        //4.读取跳出数据  转换为javabean   封装为流
        String ujTopic = "dwd_traffic_user_jump_detail";
        DataStreamSource<String> ujDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(ujTopic, groupId));
        SingleOutputStreamOperator<TrafficPageViewBean> ujJBDS = ujDS.map(new MapFunction<String, TrafficPageViewBean>() {
            @Override
            public TrafficPageViewBean map(String value) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(value);
                return new TrafficPageViewBean(
                        "",
                        "",
                        jsonObject.getJSONObject("common").getString("sc"),
                        0L,
                        0L,
                        1L,
                        0L,
                        0L,
                        jsonObject.getLong("ts")
                );

            }
        });

        //5.读取页面数据   获取页面数 停留时长  会话数  封装为流
        String pageTopic = "dwd_traffic_page_log";
        DataStreamSource<String> pageDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(pageTopic, groupId));
        SingleOutputStreamOperator<TrafficPageViewBean> pageJBDS = pageDS.map(new MapFunction<String, TrafficPageViewBean>() {
            @Override
            public TrafficPageViewBean map(String value) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(value);
                Long svCt = 0L;
                if (jsonObject.getJSONObject("page").getString("last_page_id") == null) {
                    svCt = 1L;
                }
                return new TrafficPageViewBean(
                        "",
                        "",
                        jsonObject.getJSONObject("common").getString("sc"),
                        svCt,
                        0L,
                        0L,
                        1L,
                        jsonObject.getJSONObject("page").getLong("during_time"),
                        jsonObject.getLong("ts")
                );
            }
        });

        //6.3条流 聚合
        DataStream<TrafficPageViewBean> unionDS = pageJBDS.union(ujJBDS, uvJBDS);

        //7.设置水位线
        SingleOutputStreamOperator<TrafficPageViewBean> unionWMDS = unionDS.assignTimestampsAndWatermarks(WatermarkStrategy.<TrafficPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(14))
                .withTimestampAssigner(new SerializableTimestampAssigner<TrafficPageViewBean>() {
                    @Override
                    public long extractTimestamp(TrafficPageViewBean element, long recordTimestamp) {
                        return element.getTs();
                    }
                })
        );

        //8.按照 来源分组
        KeyedStream<TrafficPageViewBean, String> keyedDS = unionWMDS.keyBy(TrafficPageViewBean::getSc);

        //9.开窗 聚合
        WindowedStream<TrafficPageViewBean, String, TimeWindow> windowDS = keyedDS.window(TumblingEventTimeWindows.of(Time.seconds(10)));
        SingleOutputStreamOperator<TrafficPageViewBean> resultDS = windowDS.reduce(new ReduceFunction<TrafficPageViewBean>() {
            @Override
            public TrafficPageViewBean reduce(TrafficPageViewBean value1, TrafficPageViewBean value2) throws Exception {
                value1.setSvCt(value1.getSvCt() + value2.getSvCt());
                value1.setUvCt(value1.getUvCt() + value2.getUvCt());
                value1.setUjCt(value1.getUjCt() + value2.getUjCt());
                value1.setPvCt(value1.getPvCt() + value2.getPvCt());
                value1.setDurSum(value1.getDurSum() + value2.getDurSum());
                return value1;
            }
        }, new WindowFunction<TrafficPageViewBean, TrafficPageViewBean, String, TimeWindow>() {
            @Override
            public void apply(String s, TimeWindow window, Iterable<TrafficPageViewBean> input, Collector<TrafficPageViewBean> out) throws Exception {
                //获取数据
                TrafficPageViewBean next = input.iterator().next();


                //补充信息
                next.setTs(System.currentTimeMillis());
                next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                next.setStt(DateFormatUtil.toYmdHms(window.getStart()));

                //输出数据
                out.collect(next);
            }
        });


        //10.将数据写入ck
        resultDS.print("===");
        resultDS.addSink(ClickHouseUtil.getJdbcSink("insert into dws_traffic_sc_new_page_view_window values(?,?,?,?,?,?,?,?,?)"));

        env.execute();
    }

}
